﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using EBE.COM.Domain;
using EBE.COM.Interfaces;

namespace EBE.COM.Data
{
  public class SubCategoryRepository : RepositoryBase, IRepository<ISubCategory>
  {
    public int CategoryId { get; set; }

    public SubCategoryRepository(string connectionString)
      : base(connectionString)
    {
    }

    public IQueryable<ISubCategory> FindAll()
    {
      throw new NotImplementedException();
    }

    public IQueryable<ISubCategory> Find(Expression<Func<ISubCategory, bool>> predicate)
    {
      var con = new SqlConnection(ConnectionString);
      var list = new List<ISubCategory>();
      using (con)
      {
        var sql = string.Format("SELECT * FROM [SubCategory]");
        var cmd = new SqlCommand(sql, con);
        con.Open();
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
          var entity = new SubCategory();
          GetEntity(reader, entity);
          list.Add(entity);
        }
      }
      // http://stackoverflow.com/questions/1299534/linq-passing-lambda-expression-as-parameter-to-be-executed-and-returned-by-meth
      return list.OrderBy(e => e.Name).AsQueryable().Where(predicate);
    }

    private static void GetEntity(IDataRecord reader, ISubCategory entity)
    {
      entity.Id = (int)reader["Id"];
      entity.CategoryId = (int)reader["CategoryId"];
      entity.Name = (string)reader["Name"];
    }

    public ISubCategory FindById(int id)
    {
      throw new NotImplementedException();
    }

    public void Add(ISubCategory newEntity)
    {
      throw new NotImplementedException();
    }

    public void Remove(ISubCategory entity)
    {
      throw new NotImplementedException();
    }

    public void Update(ISubCategory entity)
    {
      throw new NotImplementedException();
    }
  }
}
